package com.tcs.test.zk.discovery.customer;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tcs.test.zk.base.BaseZookeeper;
import com.tcs.test.zk.discovery.ServiceInfo;
import com.tcs.test.zk.watcher.TreeNodeWatcher;

public class Customer extends BaseZookeeper {
	
	private static final Logger logger = LoggerFactory.getLogger(Customer.class);
	
	@Test
	public void test() {
        try {
			this.subscribe(new ServiceInfo(
			        "service-A"
			));
//			this.subscribe(new ServiceInfo(
//			        "service-B"
//			));
		} catch (Exception e) {
			logger.error("" , e);
		}
        try {
			System.in.read();
		} catch (IOException e) {
			logger.error("" , e);
		}
	}
	
	 //本地保存了数据信息
    private Map<String, List<String>> data = Maps.newHashMap();

	public void subscribe(ServiceInfo serviceInfo) throws Exception {
        String serviceName = serviceInfo.getServiceName();
        //订阅某一个服务
        String path = TreeNodeWatcher.ZK_PATH + "/" + serviceName;
        Stat stat = cf.checkExists().forPath(path);
        if (stat == null) {
            System.out.println(serviceName + "没有服务");
            ObjectMapper om = new ObjectMapper();
            cf.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, om.writeValueAsString(serviceInfo).getBytes());
        }
        PathChildrenCache cache = new PathChildrenCache(cf, TreeNodeWatcher.ZK_PATH, true);
        //5 在初始化的时候就进行缓存监听
        cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        cache.getListenable().addListener((CuratorFramework client, PathChildrenCacheEvent event) -> {
            try {
				List<String> children = client.getChildren().forPath(path);
				data.put(serviceName, children);
				logger.info(" {} ----- {} , data : {}  " , serviceName , children , data);
			} catch (Exception e) {
				logger.error("" , e);
			}
        });
        
        new Thread() {
        	Map<String, List<String>> tempMap = null;
        	Random random = new Random();
        	public void run() {
        		while (true) {
        			try {
						Thread.sleep(3 * 1000L);
						tempMap = data;
						List<String> tempList = tempMap.get(serviceName);
						int index = random.nextInt(tempList.size());
						logger.info("tempList : {} , index : {}  , 请求了哪一个 : {} " , tempList , index , tempList.get(index));
					} catch (InterruptedException e) {
						logger.error("" , e);
					}
        		}
        	};
        }.start();
    }
}
